import React, {useEffect} from 'react';
import {Text, StyleSheet, Image, View, TouchableOpacity} from 'react-native';
import appleAuth, {
  AppleButton,
} from '@invertase/react-native-apple-authentication';
import {SafeAreaView} from 'react-native-safe-area-context';
import {loginWithApple} from '../api/api';
import {useToast} from 'react-native-toast-notifications';
import StorageUtil from '../utils/StorageUtil';
import {useDispatch} from 'redux-react-hook';
import Ionicons from 'react-native-vector-icons/Ionicons';
export default function LoginView(props) {
  const Toast = useToast();

  const dispatch = useDispatch();
  useEffect(() => {
    return appleAuth.onCredentialRevoked(async () => {
      console.warn(
        'If this function executes, User Credentials have been Revoked',
      );
    });
  }, []);

  const onAppleAuth = async () => {
    try {
      const response = await appleAuth.performRequest({
        requestedOperation: appleAuth.Operation.LOGIN,
        requestedScopes: [appleAuth.Scope.FULL_NAME, appleAuth.Scope.EMAIL],
      });
      const credentialState = await appleAuth.getCredentialStateForUser(
        response.user,
      );
      if (credentialState === appleAuth.State.AUTHORIZED) {
        let token = response.identityToken;
        let account = response.email ? response.email : ''; //不一定有
        let userName = response.fullName?.nickname
          ? response.fullName.nickname
          : ''; //不一定有
        let userID = response.user; //一定有
        let res = await loginWithApple({
          token: token,
          account: account,
          userName: userName,
          userID: userID,
        });
        if (res.success) {
          let userToken = res.data;
          StorageUtil.save('userToken', userToken);
          dispatch({type: 'SET_LOGIN', isLogin: true});
        } else {
          Toast.show(res.message);
        }
      } else {
        Toast.show('Auth Failed');
      }
    } catch (e) {
      Toast.show(e.toString());
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <Image
        source={require('../assets/LoginView/logo.png')}
        style={styles.logo}
      />
      <Text style={styles.title}>Any Live</Text>
      <View style={styles.promptContainer}>
        <Text style={styles.prompt}>Register to Get A FreeGift!</Text>
        <Image
          source={require('../assets/LoginView/gift.png')}
          style={styles.gift}
        />
      </View>
      <AppleButton
        buttonStyle={AppleButton.Style.WHITE_OUTLINE}
        buttonType={AppleButton.Type.SIGN_IN}
        style={styles.appleLoginButton}
        onPress={onAppleAuth}
      />
      <View style={styles.spacer} />
      <View style={styles.userAgreementContainer}>
        <Text style={styles.userAgreementText} numberOfLines={0}>
          By logging in, you confirm your're over 18 years old and agree to our
        </Text>
        <TouchableOpacity>
          <Text
            style={[styles.userAgreementText, styles.underline]}
            numberOfLines={0}>
            Terms & Conditions{' '}
          </Text>
        </TouchableOpacity>
        <Text style={styles.userAgreementText} numberOfLines={0}>
          and{' '}
        </Text>
        <TouchableOpacity>
          <Text
            style={[styles.userAgreementText, styles.underline]}
            numberOfLines={0}>
            Privacy Policy
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    alignItems: 'center',
    padding: 12,
  },
  title: {
    fontSize: 24,
    color: 'black',
    fontWeight: 'bold',
    marginTop: 8,
  },
  prompt: {
    fontSize: 20,
    color: 'black',
    fontWeight: 'bold',
    width: 150,
  },
  appleLoginButton: {
    width: '100%',
    height: 45,
    marginTop: 16,
  },
  logo: {
    width: 128,
    height: 128,
    marginTop: 80,
    borderRadius: 12,
  },
  promptContainer: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 50,
  },
  gift: {
    width: 64,
    height: 64,
  },
  userAgreementContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    flexWrap: 'wrap',
    marginBottom: 20,
  },
  userAgreementText: {
    color: '#888888',
    fontSize: 12,
  },
  underline: {
    textDecorationColor: '#888888',
    textDecorationLine: 'underline',
    textDecorationStyle: 'solid',
  },
  spacer: {
    flex: 1,
  },
});
